//
//  BBSController.m
//  CaiPiao
//
//  Created by l wb on 2018/5/20.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "BBSController.h"
#import "BBSCell.h"
#import "BBSReportController.h"
#import "BBSDetailController.h"
@interface BBSController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong) UIButton *selectBtn;
@property (weak, nonatomic) IBOutlet UIButton *hotBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *hotArr;
@property (strong, nonatomic) NSArray *latestArr;

@end

@implementation BBSController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"吐槽小区";
    self.selectBtn = self.hotBtn;
//    [self getBBSDataFromNet];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    if (self.selectBtn.tag == 1) {
//        [self getBBSDataFromNet];
//    }else{
        [self getBBSLatestArticlesDataFromNet];
//    }
}


-(void)getBBSDataFromNet{
    BmobQuery *query = [[BmobQuery alloc] initWithClassName:@"PopularArticles"];
//    [query orderByDescending:@"createdAt"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (!error) {
            self.hotArr = array;
            [self.tableView reloadData];

            BmobObject *object = array[0];
            NSLog(@"object--%@",object);
        }
        
    }];
}

-(void)getBBSLatestArticlesDataFromNet{
    BmobQuery *query = [[BmobQuery alloc] initWithClassName:@"Articles"];
    [query orderByDescending:@"createdAt"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (!error) {
            self.latestArr = array;
            [self.tableView reloadData];
            
        
        }
        
    }];
}



- (IBAction)titleBtnClickAction:(UIButton *)sender {
    [self changeTitleButtonColorWithBtn:self.selectBtn];
    sender.backgroundColor = kRGBColor(224, 91, 65);
    [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.selectBtn = sender;
    if (self.selectBtn.tag == 1) {
        [self getBBSDataFromNet];
    }else{
        [self getBBSLatestArticlesDataFromNet];
    }
    
}
-(void)changeTitleButtonColorWithBtn:(UIButton *)btn{
    btn.backgroundColor = [UIColor whiteColor];
    [btn setTitleColor:kRGBColor(177, 177, 177) forState:UIControlStateNormal];
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BmobObject *object;
    if (self.selectBtn.tag == 1) {
        object = self.hotArr[indexPath.row];
    } else {
         object = self.latestArr[indexPath.row];
    }
    BBSCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BBSCell"];

    
    [cell.headImg sd_setImageWithURL:[NSURL URLWithString:[object objectForKey:@"headImgUrl"] ] placeholderImage:[UIImage imageNamed:@"avatar"]];
    
    
    cell.nameLab.text = [object objectForKey:@"name"];

    cell.dateLab.text = [object objectForKey:@"createdAt"];
    
    cell.contentLab.text = [object objectForKey:@"content"];
    [cell.showImg sd_setImageWithURL:[NSURL URLWithString:[object objectForKey:@"showImg" ]] placeholderImage:[UIImage imageNamed:@"帖子占位图"]];
    
    
    cell.likeLab.text = [object objectForKey:@"likeCount"];
    cell.commentCountLab.text = [object objectForKey:@"commentCount"];
    
    cell.likeBtn.tag = indexPath.row;
    [cell.likeBtn addTarget:self action:@selector(likeBtnClickAction:) forControlEvents:UIControlEventTouchUpInside];
    NSArray *zanArr = [object objectForKey:@"zanArr"];
    cell.likeBtn.selected = NO;
    if (zanArr&&zanArr.count!=0) {
        for (NSString *str in zanArr) {
            
            if ([str isEqualToString:[BmobUser currentUser].objectId]) {
                cell.likeBtn.selected = YES;
              
            }
        }
    }
    cell.reportBtn.tag = indexPath.row;
    [cell.reportBtn addTarget:self action:@selector(reportArtitleWithBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}
-(void)reportArtitleWithBtn:(UIButton *)btn{
    if ([OpenLoginManager openLoginPageWithController:self]) {
        return;
    }
    BBSReportController *reportVC = [[UIStoryboard storyboardWithName:@"BBSStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"BBSReportController"];
  
    [reportVC showAlertView];
    [self addChildViewController:reportVC];
}

-(void)likeBtnClickAction:(UIButton *)btn{
    if ([OpenLoginManager openLoginPageWithController:self]) {
        return;
    }
    
    
    BmobObject *object;
    BBSCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:btn.tag inSection:0]];
//    if (self.selectBtn.tag == 1) {
//        object = self.hotArr[btn.tag];
//    }else{
        object = self.latestArr[btn.tag];
//    }
        NSMutableArray *zanArr = [object objectForKey:@"zanArr"];
        if (zanArr&&zanArr.count!=0) {
            for (NSString *str in zanArr) {

                if ([str isEqualToString:[BmobUser currentUser].objectId]) {
                    [zanArr removeObject:str];
                    
                    [object setObject:zanArr forKey:@"zanArr"];
                    NSInteger likeCount = [[object objectForKey:@"likeCount"] integerValue];
                    likeCount= likeCount-1;
                    [object setObject:[NSString stringWithFormat:@"%ld",likeCount] forKey:@"likeCount"];
                    
                    [object updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
//                        NSLog(@"取消赞成功");
                        btn.selected = NO;
                        cell.likeLab.text = [NSString stringWithFormat:@"%ld",likeCount];

                        
                        
                    }];
                    
                    
                }else{
                    [zanArr addObject:[BmobUser currentUser].objectId];
                    [object setObject:zanArr forKey:@"zanArr"];
                    NSInteger likeCount = [[object objectForKey:@"likeCount"] integerValue];
                    likeCount= likeCount+1;
                    [object setObject:[NSString stringWithFormat:@"%ld",likeCount] forKey:@"likeCount"];
                    [object updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
//                      NSLog(@"点赞成功");
                        btn.selected = YES;
                        cell.likeLab.text = [NSString stringWithFormat:@"%ld",likeCount];

                         }] ;
                }
            }
        }else{
            NSMutableArray *arr = [NSMutableArray new];
            [arr addObject:[BmobUser currentUser].objectId];
            [object setObject:arr forKey:@"zanArr"];
            NSInteger likeCount = [[object objectForKey:@"likeCount"] integerValue];
            likeCount= likeCount+1;
            [object setObject:[NSString stringWithFormat:@"%ld",likeCount] forKey:@"likeCount"];
            [object updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
//                NSLog(@"点赞成功");
                btn.selected = YES;
                cell.likeLab.text = [NSString stringWithFormat:@"%ld",likeCount];

            }];
        }
        
        
//    }else{
//
//    }
//
    
    
    
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 261;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BmobObject *model;
//    if (self.selectBtn.tag == 1) {
//        model = self.hotArr[indexPath.row];
//
//    } else {
        model = self.latestArr[indexPath.row];
//    }
    BBSDetailController *detail = [[UIStoryboard storyboardWithName:@"BBSStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"BBSDetailController"];
    detail.model = model;
    [self.navigationController pushViewController:detail animated:YES];
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    if (self.selectBtn.tag == 1) {
//        return self.hotArr.count;
//    } else {
        return self.latestArr.count;
//    }
    
    
}

@end
